
import XLSX from 'xlsx';
import mixin from '@/service/mixin';
import Pagination from '@/components/pagination';
import SelectAppList from '@/components/select-app-list';
import uploadFinanceFile from '@/components/upload-finance-file';

export default {
    name: 'white-list',
    components: {
        Pagination,
        SelectAppList,
        uploadFinanceFile,
    },
    mixins: [mixin],
    data() {
        return {
            form: {
                uploadDate: [],
                appName: '',
            },
            rules: {
                //
            },
            showUploadDialog: false,
            templateUrl: '/phone.xls',
            uploadForm: {
                appName: [],
                mobile: [],
                endDate: '',
            },
            uploadFormRules: {
                appName: [
                    { required: true, message: this.$t('verify.plsChoose') }, // 请选择
                ],
                endDate: [
                    { required: true, message: this.$t('verify.plsChoose') }, // 请选择
                ],
            },
            dataPickerOpt: {
                disabledDate(date) {
                    const today = new Date();
                    today.setHours(0);
                    today.setMinutes(0);
                    today.setMilliseconds(0);
                    today.setSeconds(0);
                    return date.getTime() < today.getTime();
                },
            },
        };
    },
    computed: {
        // 禁用上传按钮
        disabledUpload() {
            const { appName, endDate } = this.uploadForm;
            return !appName || !endDate;
        },
    },
    methods: {
        // 获取列表数据
        getTableData() {
            const { appName, uploadDate } = this.form;
            const params = {
                appname: appName,
                startDate: '',
                endDate: '',
            };
            if (uploadDate && uploadDate.length) {
                params.startDate = uploadDate[0];
                params.endDate = uploadDate[1];
            }
            this.$api.blackWhiteList.uploadHistory(params).then(res => {
                const { status, data } = res;
                if ('1' === status) {
                    this.tableData = data;
                    this.tableMaxHeight = document.body.clientHeight - 200;
                }
            });
        },
        // 搜索
        search() {
            this.getTableData();
        },
        // app列表选择
        getAppList(data) {
            // if (data.length > 0) {
            //     this.form.appName = data[0].name;
            //     this.getTableData();
            // }
        },
        download(row) {
            window.open(row.filePath);
        },
        showUpload() {
            this.showUploadDialog = true;
            this.uploadForm.endDate = '';
            this.uploadForm.appName = '';
        },
        submitUpload(file) {
            // console.log(file, this.uploadForm.appName)
            const { appName, endDate } = this.uploadForm;
            this.readExcelFile(file).then(data => {
                // 上传数据
                const params = {
                    appname: appName.join(','),
                    mobile: data,
                    endDate,
                };
                if (data.length === 0) {
                    this.$message.warning(this.$tc('common.plsCheckFile')); // 请检查文件数据
                    return;
                }
                this.$api.blackWhiteList.upload(params).then(res => {
                    const { status, data } = res;
                    if ('1' === status && data) {
                        this.$alert(`${this.$t('common.successAmount')}: ${data.succeedNum}, ${this.$t('common.failAmount')}: ${data.failedNum}`);
                        this.showUploadDialog = false;
                        this.getTableData();
                    }
                });
            });
        },
        getUploadAppList(data, type) {
            // console.log(data, type);
        },
        // 获取Excel文件内容
        readExcelFile(file) {
            return new Promise((resolve, reject) => {
                const dataList = [];
                const fileReader = new FileReader();
                fileReader.onload = event => {
                    try {
                        const { result } = event.target;
                        // 以二进制流方式读取得到整份Excel表格对象
                        const workbook = XLSX.read(result, {type: 'binary'});
                        let data = [];
                        const sheetName = workbook.SheetNames[0];
                        const firstSheet = workbook.Sheets[sheetName];
                        if (sheetName && firstSheet) {
                            data = data.concat(XLSX.utils.sheet_to_json(firstSheet, { header: ['phoneNum'] }));
                        }
                        // 遍历每张工作表进行读取（这里默认只读取第一张表）
                        // for (const sheet  in workbook.Sheets) {
                        //     if (workbook.Sheets.hasOwnProperty(sheet)) {
                        //         // 利用 sheet_to_json 方法将Excel转换成json数据
                        //         data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { header: ['phoneNum'] }));
                        //         break; // 如果只读取第一张表，就取消这行注释
                        //     }
                        // }
                        data.forEach(item => {
                            const phone = item['phoneNum'];
                            if (/^\d+$/.test(phone)) {
                                dataList.push(String(phone));
                            }
                        });
                        resolve(dataList);
                    } catch (e) {
                        reject('file read error');
                    }
                };
                // 以二进制方式打开
                fileReader.readAsBinaryString(file);
            });
        },
    },
    created() {
        this.getTableData();
    },
}
